﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.ArchitectureTools.CodeRepositoryQuery;
using UCL.Powersource;

namespace UCL.Powersource.Mock
{
    [DataContract]
    
    public class DummyAnalysisBridge : InitializedLifeCycleBase, IAnalysisBridge
    {
        [DataMember]
        private string databaseServerInstance = @"(localdb)\v11.0";
        [DataMember]
        private string codeIndexDatabase = "Microsoft.VsCodeIndex";

        private string connectionString;
        private List<string> ilStrings;
        private Dictionary<ITimeFrame, RepositoryEntities> CodeIndexList;

        

        public DummyAnalysisBridge(ITfsTeamProjectConfiguration p)
        {
            TeamProject = p;

           
        }
        [DataMember]
        public ITfsTeamProjectConfiguration TeamProject
        {
            get;
            private set;
        }

        public string RetrieveCodeIndexConnectionString(ITimeFrame timeFrame, bool forceRecalculate = false)
        {
            if (!IsInitialized) Initialize();
            return connectionString;
        }

        public IEnumerable<string> RetrieveDisassemblyFiles(ITimeFrame timeFrame, bool forceRecalculate = false)
        {
            if (!IsInitialized) Initialize();
            return ilStrings;
        }

        public RepositoryEntities RetrieveCodeIndex(ITimeFrame timeFrame, bool forceRecalculate = false)
        {
            if (!IsInitialized) Initialize();
            if (!CodeIndexList.ContainsKey(timeFrame) || forceRecalculate)
            {
                var conStr = RetrieveCodeIndexConnectionString(timeFrame, forceRecalculate);

                if (!CodeIndexList.ContainsKey(timeFrame))
                    CodeIndexList.Add(timeFrame, Utilities.CreateNewDBContext(conStr));
                else
                    CodeIndexList[timeFrame] = Utilities.CreateNewDBContext(conStr);
            }

            return CodeIndexList[timeFrame];
        }

        protected override bool OnInitializing()
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); ;
            builder.InitialCatalog = codeIndexDatabase;
            builder.DataSource = databaseServerInstance;
            builder.MultipleActiveResultSets = true;
            builder.IntegratedSecurity = true;
            builder.ConnectTimeout = 30;

            connectionString = builder.ConnectionString;

            string searchDir = "Where the hell am i??";
            if (Directory.GetCurrentDirectory().Contains("trunk-extensibility"))
            {
                searchDir = Directory.GetCurrentDirectory().Split(new string[] { "trunk-extensibility" }, StringSplitOptions.None).First() + "trunk-extensibility";
            }
            else if (Directory.GetCurrentDirectory().Contains("trunk"))
                searchDir = Directory.GetCurrentDirectory().Split(new string[] { "trunk" }, StringSplitOptions.None).First() + "trunk";

            ilStrings = new List<string>();
            if (searchDir != "Where the hell am i??")
            {
                var intactList = Directory.EnumerateFiles(searchDir, "*.il", SearchOption.AllDirectories);
                var r = new Random(TeamProject.UniqueId);
                int i1 = r.Next(5);
                int i2 = r.Next(5);
                while (i2 == i1) i2 = r.Next(5);
                ilStrings.Add(intactList.ElementAt(i1));
                ilStrings.Add(intactList.ElementAt(i2));
            }

            CodeIndexList = new Dictionary<ITimeFrame, RepositoryEntities>();
            return true;
        }

        protected override void OnDisposing()
        {
            return;
        }


        public RepositoryEntities RetrieveCodeIndexOrEnqueue(ITimeFrame timeFrame, bool forceRecalculate = false)
        {
            return RetrieveCodeIndex(timeFrame, forceRecalculate);
        }
    }
}
